const {override, fixBabelImports, addWebpackAlias, addWebpackExternals} = require('customize-cra');
const rewirePostcss = require('react-app-rewire-postcss');
const px2rem = require('postcss-px2rem');
const path = require('path');
const uglifyjsPlugin = require("uglifyjs-webpack-plugin");

const byPlugin = [
    //目的打包后压缩和去掉控制台输出和警告，打包过程出现:xxx.js ontains invalid source map（可忽略）
    new uglifyjsPlugin(
        {
            uglifyOptions: {
                warnings: false,
                compress: {
                    drop_debugger: true,
                    drop_console: true
                }
            }
        }
    )
];

module.exports = override(
    //按需加载
    fixBabelImports('import', {
        libraryName: 'antd-mobile',
        style: 'css',
    }),
    //不做打包处理配置，如直接以cdn引入的
    // addWebpackExternals({
    //     echarts: "window.echarts",
    // }),
    //路径别名
    addWebpackAlias({
        '@': path.resolve(__dirname, 'src'),
    }),
    (config, env) => {
        // 重写postcss
        rewirePostcss(config, {
            plugins: () => [
                require('postcss-flexbugs-fixes'),
                require('postcss-preset-env')({
                    autoprefixer: {
                        flexbox: 'no-2009',
                    },
                    stage: 3,
                }),
                //关键:设置px2rem
                px2rem({
                    remUnit: 37.5,
                    exclude: /node-modules/
                })
            ],
        });
        // 全局引入公共样式，使用时候不需再导入
        const loaders = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf;
        loaders[5].use.push({
            loader: 'sass-resources-loader',
            options: {
                resources: path.resolve(__dirname, 'src/asset/css/common.scss')//全局引入公共的scss 文件
            }
        });

        if (process.env.NODE_ENV !== "development") {
            config.devtool = false; ////去掉打包后的map文件
            config.plugins = [...config.plugins, ...byPlugin] // 打包是使用的插件
        }
        return config
    }
);

